package com.overlord.im.connector.netty.connector;

import com.google.common.base.Throwables;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.overlord.im.connector.config.ImConnectorProperty;
import com.overlord.im.connector.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * @ClassName ConnectorContext
 * @Author wuwei
 * @Description NONE
 * @Date 2020/6/1 10:27
 **/
@Slf4j
public class ConnectorContext {

    private static final BiMap<Long, ChannelHandlerContext> CONNECTOR_MAP = HashBiMap.create();

    private static ImConnectorProperty property;

    public static void put(Long clientId, ChannelHandlerContext ctx) {
        CONNECTOR_MAP.put(clientId, ctx);
        StringRedisTemplate redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(clientId.toString(), connectorProperty().getHost() + ":" + connectorProperty().getPort());
    }

    public static ChannelHandlerContext channelContext(Long clientId) {
        return CONNECTOR_MAP.get(clientId);
    }

    public static Long clientId(ChannelHandlerContext ctx) {
        return CONNECTOR_MAP.inverse().get(ctx);
    }

    public static void remove(Long clientId) {
        CONNECTOR_MAP.remove(clientId);
        StringRedisTemplate redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
        redisTemplate.delete(clientId.toString());
    }

    public static void remove(ChannelHandlerContext ctx) {
        BiMap<ChannelHandlerContext, Long> inverse = CONNECTOR_MAP.inverse();
        Long clientId = inverse.get(ctx);
        inverse.remove(ctx);
        StringRedisTemplate redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
        try {
            redisTemplate.delete(clientId.toString());
        } catch (Exception e) {
            log.error("redis删除注册信息失败,{}", Throwables.getStackTraceAsString(e));
        }
    }

    private static ImConnectorProperty connectorProperty() {
        if (property == null) {
            property = SpringContextHolder.getBean(ImConnectorProperty.class);
        }
        return property;
    }
}
